import { MessageComponent } from './message.component';
import { Injectable } from '@angular/core';
import { ExDynamicService } from '../shared/services';


@Injectable({
  providedIn: 'root'
})
export class MessageService {
  private root: any;
  private dynamic: any;
  components: Array<any> = [];

  constructor(root: MessageComponent, dynamic: ExDynamicService) {
    this.root = root;
    this.dynamic = dynamic;
  };


  show(msg: string) {
    var _this = this;
    if (this.components.length === 0 || this.components[this.components.length - 1].init) {
      this.createComponent();
    }
    // mark the component
    var /** @type {?} */ current = this.components[this.components.length - 1];
    current.init = true;
    current.instance.onDestroy = function () {
      // component detach and destroy
      _this.dynamic.destroy(current.copy);
      // remove empty item
      var /** @type {?} */ index = _this.components.findIndex(function (com) { return com.id === current.id; });
      _this.components.splice(index, 1);
    };
    var /** @type {?} */ timer = setTimeout(function () {
      current.instance.show(msg);
      clearTimeout(timer);
    }, 0);
  }


  success(msg: string) {
    this.setOptions({ type: 'success' });
    this.show(msg);
  }

  warning(msg: string) {
    this.setOptions({ type: 'warning' });
    this.show(msg);
  }

  info(msg: string) {
    this.setOptions({ type: 'info' });
    this.show(msg);
  }

  error(msg: string) {
    this.setOptions({ type: 'error' });
    this.show(msg);
  }

  setOptions(options: any) {
    if (this.components.length === 0 || this.components[this.components.length - 1].init) {
      this.createComponent();
    }
    var /** @type {?} */ last = this.components[this.components.length - 1];
    last.instance = Object.assign(last.instance, options);
  }


  createComponent() {
    var /** @type {?} */ com = this.dynamic.generator(MessageComponent);
    this.components.push({
      instance: com.instance,
      id: com.instance.id,
      copy: com,
      init: false
    });
  }
}
